package info.ferrarimarco.itEbooksDownloader.controller;

import info.ferrarimarco.java.helper.html.HtmlHelper;
import info.ferrarimarco.java.helper.http.HttpHelper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

public class BookDownloader {

	public static List<String> downloadBooks(int startIndex, int endIndex, String tagStart, String tagEnd, String destinationPath, List<String> bookNames, String baseUrl) {

		List<String> errorsList = new ArrayList<String>(endIndex - startIndex);

		int errors = 0;

		for (int i = startIndex; i <= endIndex; i++) {

			if (!bookNames.get(i).isEmpty()) {
				String[] bookData = bookNames.get(i).split(":");
				String bookNumber = bookData[0];
				String bookName = bookNumber + " - " + bookData[1];
				String url = "http://it-ebooks.info/book/" + bookNumber + "/";
				boolean downloaded = false;
				int maxTries = 100;
				int tries = 0;
				while (!downloaded && tries < maxTries) {
					try {
						String downloadUrl = getDownloadUrl(url, i, tagStart, tagEnd);
						System.out.println("Book \"" + bookName + "\" (" + bookNumber + ") download url: " + downloadUrl);

						bookName = bookName.replace("/", "-");
						bookName = bookName.replace("\\", "-");
						bookName = bookName.replace("|", "-");
						bookName = bookName.replace(":", "-");
						bookName = bookName.replace("?", "-");
						bookName = bookName.replace("<", "-");
						bookName = bookName.replace(">", "-");
						bookName = bookName.replace("*", "-");
						bookName = bookName.replace("\"", "-");

						HttpHelper.downloadFileToDisk(baseUrl + downloadUrl, destinationPath + bookName + ".pdf");
						downloaded = true;
					} catch (SocketTimeoutException e) {
						tries++;
					} catch (MalformedURLException e) {
						tries++;
					} catch (IOException e) {
						tries++;
					} catch (Throwable e) {
						tries++;
					}
				}
				if (!downloaded) {
					String logString = "ERROR DOWNLOADING book " + bookName + "\" (" + bookNumber + ") download url: " + url;
					errorsList.add(logString);
					errors++;
				}
			}
		}

		System.out.println("Books downloaded. Errors: " + errors);

		return errorsList;
	}

	public static String getDownloadUrl(String url, int bookIndex, String tagStart, String tagEnd) throws SocketTimeoutException, MalformedURLException, IOException {

		String pageSource = null;
		String downloadUrl = "";

		pageSource = HttpHelper.writeHtmltoString(url);
		downloadUrl = HtmlHelper.getTagContents(pageSource, tagStart, tagEnd);

		return downloadUrl;
	}
}
